package OrderService

import (
	"context"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"gdshop-back-end-go/common/request/OrderReq"
	"gdshop-back-end-go/common/request/TaskDataReq"
	"gdshop-back-end-go/common/response"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
)

// 关闭未支付订单
func CloseNoPayOrder(ctx context.Context, orderId int) *response.JsonResponse {
	orderModel := getOrderModel(ctx, orderId)
	if orderModel == nil {
		return response.FailByRequestMessage(nil, "找不到订单")
	}

	if orderModel.Status != 1 {
		// 当前状态已经不允许关闭，照样返回成功，删除任务
		return response.SuccessByRequestMessage(nil, "成功")
		//return response.FailByRequestMessage(nil, "订单当前不允许关闭")
	}

	jieguo := ChangeStatus(ctx, &OrderReq.ChangeStatus{
		OrderId: orderId,
		Type:    "close_order",
	})
	if jieguo.Code == 0 {
		// 如果关单成功，退还优惠券
		return GiveBackCouponByOrderId(ctx, orderId)
	}
	return jieguo
}

// CloseNoPayOrderTuan 关闭团购未付款订单
func CloseNoPayOrderTuan(ctx context.Context, orderTuanId int) *response.JsonResponse {
	// 取出 order_tuan_id 对应的团购订单
	orderTuanModel := &entity.OrderTuan{}
	err := toolsDb.GetUnSafaTable(ctx, "order_tuan").Where("id", orderTuanId).Scan(&orderTuanModel)
	if err != nil {
		return response.FailByRequestMessage(nil, "order_tuan查询失败："+err.Error())
	}
	// 取出 order_sub 订单
	orderSubModel := &entity.OrderSub{}
	err = toolsDb.GetUnSafaTable(ctx, "order_sub").Where("id", orderTuanModel.OrderSubId).Scan(&orderSubModel)
	if err != nil {
		return response.FailByRequestMessage(nil, "order_sub查询失败："+err.Error())
	}
	// 根据 order_sub 订单，退还库存
	update, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods_activity_goods_list").Where(
		"activity_id = ? and goods_id = ? and goods_option_id = ?",
		orderTuanModel.TuanId, orderSubModel.GoodsId, orderSubModel.GoodsOptionId).Update(g.Map{
		"stock": gdb.Raw("stock + " + gconv.String(orderSubModel.Total)),
	})
	if err != nil {
		return response.FailByRequestMessage(nil, "goods_activity_goods_list更新失败："+err.Error())
	}
	affected, err := update.RowsAffected()
	if err != nil {
		return response.FailByRequestMessage(nil, "goods_activity_goods_list更新失败："+err.Error())
	}
	if affected == 0 {
		return response.FailByRequestMessage(nil, "goods_activity_goods_list更新失败：没有更新到数据")
	}
	return response.SuccessByRequestMessage(nil, "成功")
}

// CloseNoPayOrderByType 按类型关闭未付款订单
func CloseNoPayOrderByTaskData(ctx context.Context, taskData TaskDataReq.CloseNoPayOrder) *response.JsonResponse {
	// 先关闭主订单
	jieguo := CloseNoPayOrder(ctx, taskData.OrderId)
	if jieguo.Code != 0 {
		return jieguo
	}
	if taskData.OrderType == 1 {
		// 团购订单，退还库存
		return CloseNoPayOrderTuan(ctx, gconv.Int(taskData.OtherData["order_tuan_id"]))
	}

	return jieguo
}
